package com.copro.chemdb.ques;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;

import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryCallback;

public class QuesUtils {

	/**
	 * Provide the query function for list
	 * 
	 * @author zozoh
	 * 
	 */
	static class ListGetter implements QueryCallback {

		private List<Questionnaire> list;

		public ListGetter(List<Questionnaire> list) {
			this.list = list;
		}

		public List<Questionnaire> getList() {
			return this.list;
		}

		@Override
		public void exec(ResultSet rs) throws SQLException {
			while (rs.next()) {
				list.add(new Questionnaire(rs));
			}
		}
	}

	/**
	 * Provide the query function for one object
	 * 
	 * @author zozoh
	 * 
	 */
	static class DetailGetter implements QueryCallback {

		private Questionnaire ques;

		public DetailGetter(Questionnaire ques) {
			this.ques = ques;
		}

		public Questionnaire getObject() {
			return this.ques;
		}

		@Override
		public void exec(ResultSet rs) throws SQLException {
			if (rs.first())
				this.ques = new Questionnaire(rs);

		}

	}

	public static List<Questionnaire> getRoots(Application app)
			throws SimpleException {
		ListGetter callback = new ListGetter(new LinkedList<Questionnaire>());
		SQLSegment sql = app.getSQL("rootQues");
		app.query(sql.toString(), callback);
		return callback.getList();
	}

	public static List<Questionnaire> getAll(Application app)
			throws SimpleException {
		ListGetter callback = new ListGetter(new LinkedList<Questionnaire>());
		SQLSegment sql = app.getSQL("allQues");
		app.query(sql.toString(), callback);
		return callback.getList();
	}

	public static List<Questionnaire> getChildren(Application app, int id)
			throws SimpleException {
		ListGetter callback = new ListGetter(new LinkedList<Questionnaire>());
		SQLSegment sql = app.getSQL("childQues");
		sql.set("id", id);
		app.query(sql.toString(), callback);
		return callback.getList();
	}

	public static Questionnaire getById(Application app, int id)
			throws SimpleException {
		SQLSegment sql = app.getSQL("getQues");
		sql.set("id", id <= 0 ? "NULL" : id);
		DetailGetter callback = new DetailGetter(new Questionnaire());
		app.query(sql.toString(), callback);
		return callback.getObject();
	}
}
